package edu.iss.javaproject.validator;

import java.util.Calendar;
import java.util.Date;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

import edu.iss.javaproject.model.LeaveRecord;

@Component
public class LeaveValidatorImpl implements LeaveValidator {

	@Override
	public boolean supports(Class<?> clazz) {
		return LeaveRecord.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "leaveStart", "leaveRecord.leaveStart.empty", "Start date is required.");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "leaveEnd", "leaveRecord.leaveEnd.empty", "End date is required.");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "duration", "leaveRecord.duration.empty", "Duration is required.");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "additionalReason", "leaveRecord.additionalReason.empty", "Reason is required.");
	}
	
	@Override
	public boolean checkDates(LeaveRecord leaveRecord) {
		if(checkStartEndDate(leaveRecord) == false ||
				checkWorkingDays(leaveRecord) == false){
			return false;
		} else {
			return true;
		}
	}

	private boolean checkStartEndDate(LeaveRecord leaveRecord) {
		Date startDate = leaveRecord.getLeaveStart();
		Date endDate = leaveRecord.getLeaveEnd();
		if(startDate.before(endDate) || startDate.equals(endDate)){
			return true;
		} else {
		return false;
		}
	}

	private boolean checkWorkingDays(LeaveRecord leaveRecord) {
		Date startDate = leaveRecord.getLeaveStart();
		Date endDate = leaveRecord.getLeaveEnd();
		
		Calendar cal1 = Calendar.getInstance();
		Calendar cal2 = Calendar.getInstance();
		cal1.setTime(startDate);
		cal2.setTime(endDate);
		
		if ((Calendar.SATURDAY == cal1.get(Calendar.DAY_OF_WEEK)) || 
				(Calendar.SUNDAY == cal1.get(Calendar.DAY_OF_WEEK)) ||
				(Calendar.SATURDAY == cal1.get(Calendar.DAY_OF_WEEK)) || 
				(Calendar.SUNDAY == cal1.get(Calendar.DAY_OF_WEEK))) {
			return false;
		} else {
			return true;
		}
	}

	


}
